package com.Pawtrack.web.controller.system;

import java.util.List;
import java.util.Set;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.Pawtrack.common.constant.Constants;
import com.Pawtrack.common.core.domain.AjaxResult;
import com.Pawtrack.common.core.domain.entity.SysMenu;
import com.Pawtrack.common.core.domain.entity.SysUser;
import com.Pawtrack.common.core.domain.model.LoginBody;
import com.Pawtrack.common.core.domain.model.LoginUser;
import com.Pawtrack.common.utils.SecurityUtils;
import com.Pawtrack.framework.web.service.SysLoginService;
import com.Pawtrack.framework.web.service.SysPermissionService;
import com.Pawtrack.framework.web.service.TokenService;
import com.Pawtrack.system.service.ISysMenuService;
import com.Pawtrack.common.core.redis.RedisCache;
import com.Pawtrack.common.utils.StringUtils;
import com.Pawtrack.framework.manager.AsyncManager;
import com.Pawtrack.framework.manager.factory.AsyncFactory;
import com.Pawtrack.system.service.ISysUserService;
import com.Pawtrack.common.constant.UserConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PutMapping;
import com.Pawtrack.common.core.domain.entity.SysRole;
import java.util.HashSet;

/**
 * 登录验证
 * 
 * @author lch
 */
@RestController
public class SysLoginController
{
    private static final Logger log = LoggerFactory.getLogger(SysLoginController.class);

    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private RedisCache redisCache;
    @Autowired
    private com.Pawtrack.system.service.ISysUserService userService;

    /**
     * 登录方法
     * 
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody)
    {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 发送短信验证码（防刷、日志、短信服务预留）
     */
    @PostMapping("/login/sendSmsCode")
    public AjaxResult sendSmsCode(@RequestBody Map<String, String> params, HttpServletRequest request) {
        String phone = params.get("phone");
        if (phone == null || !phone.matches("^1[3-9]\\d{9}$")) {
            return AjaxResult.error("手机号格式不正确");
        }
        String key = "SMS_SEND_LIMIT_" + phone;
        Integer count = redisCache.getCacheObject(key);
        if (count == null) count = 0;
        if (count >= 5) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(phone, Constants.LOGIN_FAIL, "短信验证码请求过于频繁"));
            return AjaxResult.error("请求过于频繁，请稍后再试");
        }
        redisCache.setCacheObject(key, count + 1, 1, TimeUnit.MINUTES);
        String code = String.valueOf((int)((Math.random()*9+1)*100000));
        redisCache.setCacheObject("SMS_CODE_" + phone, code, 5, TimeUnit.MINUTES);
        // TODO: 调用短信平台发送验证码
        System.out.println("【调试用】手机号 " + phone + " 验证码：" + code);
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(phone, Constants.LOGIN_SUCCESS, "短信验证码已发送"));
        return AjaxResult.success("验证码已发送");
    }

    /**
     * 手机号+验证码登录（自动注册、日志）
     */
    @PostMapping("/login/phone")
    public AjaxResult phoneLogin(@RequestBody Map<String, String> params) {
        String phone = params.get("phone");
        String code = params.get("code");
        if (phone == null || code == null) {
            return AjaxResult.error("参数错误");
        }
        String cacheCode = redisCache.getCacheObject("SMS_CODE_" + phone);
        if (cacheCode == null || !cacheCode.equals(code)) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(phone, Constants.LOGIN_FAIL, "验证码错误或已过期"));
            return AjaxResult.error("验证码错误或已过期");
        }
        SysUser user = userService.selectUserByPhone(phone);
        if (user == null) {
            user = new SysUser();
            user.setUserName("u" + phone);
            user.setPhonenumber(phone);
            user.setNickName("用户" + phone.substring(7));
            user.setPassword(SecurityUtils.encryptPassword("123456"));
            userService.insertUser(user);
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(phone, Constants.REGISTER, "手机号自动注册"));
        }
        LoginUser loginUser = new LoginUser(user.getUserId(), user.getDeptId(), user, permissionService.getMenuPermission(user));
        String token = tokenService.createToken(loginUser);
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(phone, Constants.LOGIN_SUCCESS, "手机号验证码登录成功"));
        AjaxResult ajax = AjaxResult.success();
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }



    /**
     * 获取用户信息
     */
    @GetMapping("/getInfo")
    public AjaxResult getInfo() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser currentUser = loginUser.getUser();
        currentUser.setPassword(null);
        
        // 获取用户角色和权限
        List<SysRole> roles = currentUser.getRoles();
        Set<String> permissions = loginUser.getPermissions();
        
        // 提取角色名称
        Set<String> roleNames = new HashSet<>();
        if (roles != null) {
            for (SysRole role : roles) {
                roleNames.add(role.getRoleKey());
            }
        }
        
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", currentUser);
        ajax.put("roles", roleNames);
        ajax.put("permissions", permissions);
        
        return ajax;
    }



    /**
     * 获取路由信息
     * 
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters()
    {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }
}
